<?php
namespace App\Exception\Handler;

use Hyperf\Di\Annotation\Inject;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\FooException;
use Throwable;


class FooExceptionHandler extends  ExceptionHandler
{
    /**
     * @Inject
     *
     * @var \Hyperf\HttpServer\Contract\ResponseInterface as httpResponse
     */
    protected $httpResponse;

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof FooException) {
            // 格式化输出
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => $throwable->getMessage(),
                'line' => $throwable->getLine(),
                'file' => $throwable->getFile(),
            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            // 阻止异常冒泡
            $this->stopPropagation();

            //这里我不想让他报 "Internal Server Error."这个错误，所以返回错误信息
            //return $response->withStatus(500)->withBody(new SwooleStream($data));

            $code = $throwable->getCode();
            $msg = $throwable->getMessage();
            //自定义异常处理
            //return $this->httpResponse->json(['msg' => 'token失效了', 'code' => 500, 'data' => $data]);
            return $this->httpResponse->json(['code' => $code, 'msg' => $msg, 'data' => new \ArrayObject()]);
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
